package qit.itmiaojie.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import qit.itmiaojie.pojo.Role;
import qit.itmiaojie.pojo.User;
import qit.itmiaojie.service.RoleService;
import qit.itmiaojie.service.UserService;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController  {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;




    /**
     * 删除用户
     * @param
     */
    @RequestMapping("/login")
    public String del(String username, String password, HttpSession session) {
        System.out.println(username + password);
        User user = userService.login(username,password);
        System.out.println(user);
        if (user != null){
            session.setAttribute("user",user);
            return "redirect:/index.jsp";
        }
        return "redirect:/login.jsp";
    }

    /**
     * 删除用户
     * @param id
     */
    @RequestMapping("/del/{id}")
    public String del(@PathVariable(value = "id") Long id){
       userService.del(id);
       return "redirect:/user/findAll";
    }
    /**
     * add用户
     * @param user
     * @param roleIds
     * @return
     */
    @RequestMapping("/save")
    public String save(User user,long[] roleIds){
        System.out.println("test save ...");
        userService.save(user,roleIds);
        return "redirect:/user/findAll";
    }

    /**
     * 在新建窗口中显示所有角色
     * @param modelAndView
     * @return
     */
    @RequestMapping("/addUI")
    public ModelAndView add(ModelAndView modelAndView){
        List<Role> roleList = roleService.findAll();
        modelAndView.addObject(roleList);
        modelAndView.setViewName("user-add");
        return modelAndView;

    }

    /**
     * 查询所有角色
     * @param modelAndView
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(ModelAndView modelAndView){
        List<User> userList = userService.findAll();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }
}
